# -*- coding: utf-8 -*-
from django import forms
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from google.appengine.ext.db import djangoforms
from google.appengine.ext import db

from base.models import Staff, StaffManager, School
from base.util.decorators import render_to, login_required, admin_required
import logging


@login_required
@render_to('staff/list.html')
def list(request):
    staffs = Staff.all().fetch(100)
    return {'staffs': staffs}

class StaffForm(djangoforms.ModelForm):
    class Meta:
        model = Staff
        exclude = ('id',)

    def clean(self):
        cleaned_data = self.cleaned_data
        first_name = cleaned_data.get('first_name')
        staff = StaffManager.is_exist(first_name)
        if not self.instance and staff:
            raise forms.ValidationError(u'같은 staff이 이미 존재합니다.')
        if self.instance:
            if self.instance.first_name != first_name and staff:
                raise forms.ValidationError(u'같은 staff이 이미 존재합니다.')
        return cleaned_data

@admin_required
@render_to('staff/form.html')
def create(request):
    form = StaffForm()
    if request.method == 'POST':
        form = StaffForm(request.POST)
        if form.is_valid():
            staff = form.save(commit=False)
            staff.put()
            return staff.get_absolute_url
    return {'form': form}

@admin_required
@render_to('staff/detail.html')
def detail(request, staff_id):
    staff =  Staff.get_using_id(int(staff_id))

    schools = School.gql('WHERE coordinator=:staff ORDER BY name ASC', staff=staff).fetch(100)
    return {
        'staff': staff,
        'schools': schools,
        }

@admin_required
@render_to('staff/form.html')
def change(request, staff_id):
    staff = Staff.get_using_id(int(staff_id))
    form = StaffForm(request.POST or None, instance=staff)
    if form.is_valid():
        staff = form.save()
        return staff.get_absolute_url
    return {'form': form}

@admin_required
@render_to('staff/list.html')
def delete(request, staff_id):
    staff = Staff.get_using_id(int(staff_id))
    staff.delete()
    return HttpResponseRedirect(reverse('base.views.staff.list', args=()))

